package edu.gatech.arktos;

import java.net.URL;

import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.SpreadsheetFeed;

public class Session {
	private SpreadsheetService service;
	private URL feedurl;
	private SpreadsheetFeed feed;

	public Session(){

	}

	/**
	 * Make call to Google servers and verifies if username and passwords are correct
	 * @param user
	 * @param pw
	 * @return 0 if correct, 1 if not
	 */
	public int login(String user, String pw)
	{
		try
		{
			service = new SpreadsheetService("myservice");
			service.setUserCredentials(user,pw);
			feedurl = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
			feed = service.getFeed(feedurl, SpreadsheetFeed.class);	
			return 0;
		}
		catch(Exception e)
		{
			//System.out.println("Exception " + e.getMessage());
			return 1;
		}


		// Send to server: user, pw
		// listen for response
	}

	/**
	 * Logs the user out
	 * @return 0 if successful
	 */
	public int logout(){
		return 0;
	}

	/**
	 * Checks with google and return the database specified by the name we passed in.
	 * @param dbName - database name
	 * @return db - the database object
	 */
	public GradesDB getDBByName(String dbName){
		String sheetTitle;
		for(int i = 0; i < feed.getEntries().size(); i++)
		{
			sheetTitle = feed.getEntries().get(i).getTitle().getPlainText();

			if(sheetTitle.equals(dbName)){
				SpreadsheetEntry entry = feed.getEntries().get(i);
				return new GradesDB(entry);
			}
		}
		return null;
	}
}
